<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="false">
        <!-- <span slot="before">共166条记录</span> -->
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button v-if="checkPermission('exportEmployee')" size="small" type="danger" @click="exportEmpioyees">导出</el-button>
          <el-button v-if="checkPermission('addEmployee')" size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="EmpioyeesBasicList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" align="center">
            <template #default="{row}">
              <img
                v-imgerr="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto "
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
                @click="showAvatar(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formOfEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry" />
          <!-- <template #default="{row}">{{ row.timeOfEntry }}</template>
          </el-table-column> -->
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template #default="{row}">
              <el-switch
                :value="row.enableState === 1"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <!-- <template> -->
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <!-- <el-button type="text" size="small" @click="isShowRole=true">角色</el-button> -->
              <el-button type="text" size="small" @click="delEmpioyees(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :total="page.total" :page-sizes="page.size" @current-change="currentChange" />
        </el-row>
      </el-card>
      <addDemployee :show-dialog.sync="showDialog" :add-employee="getEmpioyeesBasicList" />
      <!-- 弹窗显示二维码 -->
      <el-dialog :visible="isShowAvatar" @close="isShowAvatar=false">
        <el-row type="flex" justify="center">
          <canvas ref="myAvatar" />
        </el-row>
      </el-dialog>
      <!-- 弹窗分配角色 -->
      <assignRole ref="assignRoles" :is-show-role.sync="isShowRole" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getEmpioyeesBasicList, delEmpioyees } from '@/api/employees'
import addDemployee from './components/add-employee'
import employeesnum from '@/api/constant/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '../../filters/index'
import QRCode from 'qrcode'
import assignRole from './components/assignRole.vue'
export default {
  components: { addDemployee, assignRole },
  data() {
    return {
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      EmpioyeesBasicList: [],
      showDialog: false,
      isShowAvatar: false,
      isShowRole: false,
      userId: ''
    }
  },
  created() {
    this.getEmpioyeesBasicList()
  },
  methods: {
    // 全局注册了
    // checkPermission(pointName) {
    //   // 如果这个名称存在于当前用户的points数组中，就可以点击，否则不可
    //   return this.$store.getters.points.includes(pointName)
    // },
    //   加载所有员工的数据
    async exportEmpioyees() {
      const { rows } = await getEmpioyeesBasicList({ page: 1, size: this.page.total })
      console.log(rows)
      const header = [
        '手机号',
        '姓名',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]
      const data = rows.map(userObj => {
        return this.objToarr(userObj, header)
      })
      export_json_to_excel({
        header,
        data
      })
    },
    objToarr(userObj, header) {
      const userArr = []
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      header.forEach(key => {
        const enKey = dict['key']
        let value = userObj[enKey]
        if (enKey === 'formOfEmployment') {
          const obj = employeesnum.hireType.find(item => item.id === value)
          obj ? obj.value : '未知形式'
        }
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          value = formatDate(value)
        }
        userArr.push(value)
      })
      return userArr
    },
    // 获取用户的基本信息
    async getEmpioyeesBasicList() {
      const { rows, total } = await getEmpioyeesBasicList(this.page)
      this.EmpioyeesBasicList = rows
      this.page.total = total
      // console.log(this.EmpioyeesBasicList)
    },
    // 分页设置
    currentChange(currentPage) {
      this.page.page = currentPage
      this.getEmpioyeesBasicList()
    },
    // 内容格式化
    formOfEmployment(row, column, cellValue, index) {
      // find方法：找到一个符合条件的立马返回数据，不再进行遍历；
      // some方法：找到符合条件的返回true，找不到返回false；
      const obj = employeesnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },

    // 删除
    async delEmpioyees(id) {
      await this.$confirm('确定删除吗？')
      await delEmpioyees(id)
      this.$message.success('删除成功')
      this.getEmpioyeesBasicList()
    },
    showAvatar(url) {
      console.log(url)
      if (url) {
        this.isShowAvatar = true
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.myAvatar, url, {
            width: 300,
            color: {
              dark: '#66b1ff'
            }
          })
        })
      }
    },
    // 角色分配
    async  assignRole(id) {
      await this.$refs.assignRoles.getCheckedRole(id)
      this.userId = id
      this.isShowRole = true
    }
  }
}
</script>

<style>

</style>
